<?php

namespace app\common\model\general;

use my\Lnglat;
use think\Model;
use traits\model\SoftDelete;


class LihuaStore extends Model
{
    // 表名
    protected $table = 'lihua_store';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    // 追加属性
    protected $append = [];


    public function getStatusList()
    {
        return ['0' => '禁用', '1' => '启用'];
    }

    // 获取城市门店
    public static function getCityStoreList($city_id = 0)
    {
        $list = self::all(function ($query) use ($city_id) {
            $query->where(['city_id' => $city_id, 'status' => 1])->field('id,name')->order('id', 'asc');
        });
        return $list;
    }

    // 根据经纬度获取归属门店
    public static function getPointStore($city_id, $lng, $lat)
    {
        $store = ['id' => 0, 'name' => '', 'city_id' => 0, 'doorshop' => 0, 'tel' => '', 'addr' => '', 'lng' => '', 'lat' => '' ];
        if (is_numeric($lng) && is_numeric($lat)) {
            $map = $city_id > 0 ? ['city_id' => $city_id, 'status' => 1] : ['status' => 1];
            $list = self::all(function ($query) use ($map) {
                $query->where($map)->field('id,name,city_id,area,doorshop,tel,addr,lng,lat, manager_tel')->order('id', 'asc');
            });
            foreach ($list as $k => $v) {
                if ($v['area']) {
                    $area = json_decode($v['area'], true);
                    if (is_null($area)) continue;
                    if (Lnglat::isPointInPolygon([$lng, $lat], $area)) {
                        $store = $list[$k];
                        unset($store['area']);
                        break;
                    }
                }
            }
        }
        return $store;
    }

    // 关联城市模型
    public function lihuacity()
    {
        return $this->belongsTo('app\common\model\general\LihuaCity', 'city_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

}
